package org.dromara.common.social.maxkey

import me.zhyd.oauth.cache.AuthStateCache
import me.zhyd.oauth.config.AuthConfig
import me.zhyd.oauth.exception.AuthException
import me.zhyd.oauth.model.AuthCallback
import me.zhyd.oauth.model.AuthToken
import me.zhyd.oauth.model.AuthUser
import me.zhyd.oauth.request.AuthDefaultRequest
import org.dromara.common.core.utils.SpringUtils.getProperty
import org.dromara.common.json.utils.JsonUtils.parseMap
import org.dromara.common.social.maxkey.AuthMaxKeySource

/**
 * @author LikeYouDo
 * @date 2025/7/20
 */

/**
 * 设定归属域
 */
class AuthMaxKeyRequest : AuthDefaultRequest {

    companion object {
        @JvmField
        val SERVER_URL: String = getProperty("justauth.type.maxkey.server-url")
    }

    constructor(config: AuthConfig) : super(config, AuthMaxKeySource.MAXKEY)

    constructor(config: AuthConfig, authStateCache: AuthStateCache) : super(config, AuthMaxKeySource.MAXKEY, authStateCache)

    override fun getAccessToken(authCallback: AuthCallback): AuthToken {
        val body = doPostAuthorizationCode(authCallback.code)
        val obj = parseMap(body)

        obj ?: throw AuthException("获取用户信息失败")

        // oauth/token 验证异常
        if (obj.containsKey("error")) {
            throw AuthException(obj.getStr("error_description"))
        }
        // user 验证异常
        if (obj.containsKey("message")) {
            throw AuthException(obj.getStr("message"))
        }
        return AuthToken.builder()
            .accessToken(obj.getStr("access_token"))
            .refreshToken(obj.getStr("refresh_token"))
            .idToken(obj.getStr("id_token"))
            .tokenType(obj.getStr("token_type"))
            .scope(obj.getStr("scope"))
            .build()
    }

    override fun getUserInfo(authToken: AuthToken): AuthUser {
        val body = doGetUserInfo(authToken)
        val obj = parseMap(body)

        obj ?: throw AuthException("获取用户信息失败")

        // oauth/token 验证异常
        if (obj.containsKey("error")) {
            throw AuthException(obj.getStr("error_description"))
        }
        // user 验证异常
        if (obj.containsKey("message")) {
            throw AuthException(obj.getStr("message"))
        }
        return AuthUser.builder()
            .uuid(obj.getStr("userId"))
            .username(obj.getStr("username"))
            .nickname(obj.getStr("displayName"))
            .avatar(obj.getStr("avatar_url"))
            .blog(obj.getStr("web_url"))
            .company(obj.getStr("organization"))
            .location(obj.getStr("location"))
            .email(obj.getStr("email"))
            .remark(obj.getStr("bio"))
            .token(authToken)
            .source(source.toString())
            .build()
    }


}
